package com.gaeainfo.websocket;

import com.gaeainfo.constant.GaeaConstant;
import com.gaeainfo.framework.core.basic.GaeaContainerProxy;
import com.gaeainfo.framework.core.utils.common.GaeaCommonUtil;
import com.gaeainfo.modules.mobile.service.MobileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Caven on 2018/1/17.
 */
public class WebSocketHandlerHub extends TextWebSocketHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    private static final Map<String, WebSocketSession> users;

    static {
        users = new HashMap();
    }


    /**
     * 连接成功时候，会触发页面上onopen方法
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        try {
            String userId = (String) session.getAttributes().get("userId");
            users.put(userId, session);
            String isMobile = (String) session.getAttributes().get("isMobile");
            if ("1".equals(isMobile)) {
                String deptId = (String) session.getAttributes().get("deptId");
                String policeNo = (String) session.getAttributes().get("policeNo");
                String policeName = (String) session.getAttributes().get("policeName");
                MobileService mobileService = GaeaContainerProxy.getInstance().getBean("mobileService");
                mobileService.createMobileStatus(deptId, policeNo, policeName, GaeaConstant.MobileStatus.BACKUP);
            }
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
        }

    }

    /**
     * 关闭连接时触发
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        try {
            String userId = (String) session.getAttributes().get("userId");
            users.remove(userId);
            String isMobile = (String) session.getAttributes().get("isMobile");
            if ("1".equals(isMobile)) {
                String policeNo = (String) session.getAttributes().get("policeNo");
                String deptId = (String) session.getAttributes().get("deptId");
                String policeName = (String) session.getAttributes().get("policeName");
                MobileService mobileService = GaeaContainerProxy.getInstance().getBean("mobileService");
                mobileService.createMobileStatus(deptId, policeNo, policeName, GaeaConstant.MobileStatus.OFFLINE);
            }
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
        }
    }

    /**
     * js调用websocket.send时候，会调用该方法
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws IOException {
        String userId = (String) session.getAttributes().get("userId");
        if (users.get(userId) != null && users.get(userId).isOpen()) {
            users.get(userId).close();
        }
        users.remove(userId);
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }


    /**
     * 发送消息
     *
     * @param userId
     * @param message
     */
    private void sendMessage(String userId, TextMessage message) {
        WebSocketSession user = users.get(userId);
        try {
            if (user != null && user.isOpen()) {
                user.sendMessage(message);
            }
        } catch (Exception e) {
            logger.error(GaeaCommonUtil.getStackTrace(e));
        }
    }

    /**
     * 发送单个用户消息
     *
     * @param userId
     * @param message
     */
    private void sendMessageToUser(String userId, String message) {
        TextMessage textMessage = new TextMessage(message);
        this.sendMessage(userId, textMessage);
    }

    /**
     * 给所有用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(String message) {
        for (String key : users.keySet()) {
            this.sendMessageToUser(key, message);
        }
    }

    /**
     * 给单部门用户发送消息
     *
     * @param deptId
     * @param message
     */
    public void sendMessageToDept(String deptId, String message) {
        TextMessage textMessage = new TextMessage(message);
        for (String key : users.keySet()) {
            if (key.startsWith(deptId)) {
                this.sendMessage(key, textMessage);
            }
        }
    }


    /**
     * 给所有部门用户发送消息
     *
     * @param deptIds
     * @param message
     */
    public void sendMessageToDepts(String[] deptIds, String message) {
        for (String deptId : deptIds) {
            this.sendMessageToDept(deptId, message);
        }
    }

}
